import json

import config
from client.client import Client
from client.sendProp import sendProp
from client.tdmg import manager
from dataTemp.temp import Mes
from taskPro import taskPro


def run(client: Client):
    while True:
        response = client.receive_message()
        msg = parse_message(response)
        handle_message(msg,client)

def receive_message(sock):
    try:
        data = sock.recv(4096)
        if not data:
            return None
        json_str = data.decode('utf-8')
        return json_str
    except Exception as e:
        print(f"Error receiving message: {e}")
        return None

def parse_message(json_str):
    try:
        message = json.loads(json_str)
        return message
    except json.JSONDecodeError as e:
        print(f"JSON decode error: {e}")
        return None

def handle_message(message,server:Client):
    if message is None:
        print("No message to handle")
        return
    message_type = message.get('Type')
    data = message.get('Data')

    if message_type == "标签":
        try:
            labels = json.loads(data)
            config.labs=labels
            manager.start_thread(sendProp, args=(server,))
            # thread = threading.Thread(target=sendProp,args=(server,))
            # thread.start()
            print("Received labels:", labels)
        except json.JSONDecodeError as e:
            print(f"Error decoding labels: {e}")
    elif message_type == "goToBuWanJia_RMT":
        ast=taskPro.getAction("goToBuWanJia")
        s=ast.click()
        mes=Mes("goToBuWanJia_MT",json.dumps(s))
        server.send_message(mes)
    elif message_type == "repairEquip_RMT":
        ast = taskPro.getAction("repairEquip")
        s = ast.click()
        mes = Mes("repairEquip_MT",json.dumps(s))
        server.send_message(mes)
    elif message_type == "cutPlayer2_RMT":
        # s = chooseCharacter(int(message.Data))
        # mes = Mes("cutPlayer2_MT",json.dumps(s))
        # server.send_message(mes)
        print(0)
    elif message_type == "backTown_RMT":
        ast = taskPro.getAction("backTown")
        s = ast.click()
        mes = Mes("backTown_MT",json.dumps(s))
        server.send_message(mes)
    else:
        print(f"Unknown message type: {message_type}")


